<?php
/**
 * Created by PhpStorm.
 * User: waixiu
 * Date: 2017/6/15
 * Time: 15:03
 */

namespace App\Libs;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;
use Ixudra\Curl\Facades\Curl;

//define("token", "weixin");
//define("AppID", "wx1985bd0909bbc1f9");
//define("EncodingAESKey", "NQRc2EskoLyejQsPgfhOUj2cPyRDmDhzv2G4IjxRylA");
//if(strtolower($_SERVER['REQUEST_METHOD']) == 'get') {
//    file_put_contents('weixin_log.txt', "IP=".$_SERVER['REMOTE_ADDR'].PHP_EOL,FILE_APPEND); //记录访问IP到log日志
//    file_put_contents('weixin_log.txt', "QUERY_STRING=".$_SERVER['QUERY_STRING'].PHP_EOL,FILE_APPEND);//记录请求字符串到log日志
//    file_put_contents('weixin_log.txt', '$_GET[echostr])='.htmlspecialchars($_GET['echostr']).PHP_EOL,FILE_APPEND); //记录是否获取到echostr参数
//    exit(htmlspecialchars($_GET['echostr']));      //把echostr参数返回给微信开发者后台
//}
class wechatCallbackapiTest
{
    private $token;
    private $encodingAESKey;
    private $appid;
    private $secret;
    public function __construct()
    {
        $this->token = 'weixin';
        $this->encodingAESKey = env('WX_SF_AESKEY', 'NQRc2EskoLyejQsPgfhOUj2cPyRDmDhzv2G4IjxRylA');
        $this->appid = env('WX_SF_APPID', 'wx6c157d026dceea76');
        $this->secret = env('WX_SF_SECRET','2bcd2b9f480f857eb62a85eb5fef1a7a');
    }

     //验证签名
     public function valid()
     {
         savelog('newweixin.log', date('Y-m-d H:i:s').'返回明文:'.json_encode($_GET));
         $echoStr = $_GET["echostr"];
         $signature = $_GET["signature"];
         $timestamp = $_GET["timestamp"];
         $nonce = $_GET["nonce"];
         $tmpArr = array($this->token, $timestamp, $nonce);
         sort($tmpArr);
         $tmpStr = implode($tmpArr);
         $tmpStr = sha1($tmpStr);
         if($tmpStr == $signature)
         {
            return $echoStr;
            exit;
         }
    }

     //响应消息
    public function responseMsg()
    {
        //$timestamp  = isset($_GET['timestamp'])?$_GET['timestamp']:'';
        //$nonce = $_GET["nonce"];
        //$msg_signature = $_GET['msg_signature'];
        $encrypt_type = (isset($_GET['encrypt_type']) && ($_GET['encrypt_type'] == 'aes')) ? "aes" : "raw";
        $postStr = file_get_contents('php://input');
        savelog('newweixin.log', date('Y-m-d H:i:s').'返回明文:'.$postStr);
        if (!empty($postStr))
        {
             //解密
            if ($encrypt_type == 'aes')
            {
                //$pc = new wxBizMsgCrypt($this->token, $this->encodingAESKey,  $this->appid);
                $decryptMsg = "";  //解密后的明文
                //$errCode = $pc->decryptMsg($msg_signature, $timestamp, $nonce, $postStr, $decryptMsg);
                $postStr = $decryptMsg;
            }

            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            if(!$postObj) {
                //Storage::disk('test')->append('success.log',date('Y-m-d H:i:s').'返回明文:'.$postStr);
                //savelog('newweixin.log', date('Y-m-d H:i:s').'返回明文:'.$postStr);
                return '';
            }
            $RX_TYPE = $postObj ? trim($postObj->MsgType) : '';
            $result = '';
            switch ($RX_TYPE)
            {
                case "event":
                     $result = $this->receiveEvent($postObj);
                     break;
                case "text":
                    $result = $this->receiveText($postObj);
                    break;
            }
            if (!$result) {
                return '';
            }
            //Storage::disk('test')->append('success.log',date('Y-m-d H:i:s').'返回明文:'.$result);
             //加密
             if ($encrypt_type == 'aes')
             {
                 $encryptMsg = ''; //加密后的密文
                 //$errCode = $pc->encryptMsg($result, $timestamp, $nonce, $encryptMsg);
                 $result = $encryptMsg;
             }
             return $result;
        }else
        {
             return "1111";
             exit;
        }
   }
    private function receiveEvent($object)
    {
        try{
            $debug = false;
            /*if (isset($object->ToUserName)&& (in_array($object->ToUserName, ['gh_fcb12de53340','gh_c154d2bbf88a']))) {
                $debug = true;
                savelog('fans_error1',print_r($object,1));
            }*/
            $result = 1;
            switch ($object->Event)
            {

                case "subscribe":
                    $content = "";
                    //获取用户信息 只有服务号才可以
                    $users = $this->getAuthInfo($object->FromUserName, $object->ToUserName);//关注用户微信信息
                    /*$officialAccount = EasyWeChat::officialAccount();
                    $users = $officialAccount->user->get($object->FromUserName);*/
                    savelog('newweixinuser.log', json_encode($users));
                    if(isset($users['errcode']) && $users['errcode'] != 0)
                    {
                        savelog('fans_error.log',print_r($users,1).'ToUserName:'.$object->ToUserName);
                    }
                    $userInfo = '';
                    /*if(count($users) >0)
                    {
                        $str = '';
                        $nickname = (isset($users['nickname']) && !empty($users['nickname'])) ? $users['nickname'] : '';
                        $language = (isset($users['language']) && !empty($users['language'])) ? $users['language'] : '';
                        $city = (isset($users['city']) && !empty($users['city'])) ? $users['city'] : '';
                        $province = (isset($users['province']) && !empty($users['province'])) ? $users['province'] : '';
                        $country = (isset($users['country']) && !empty($users['country'])) ? $users['country'] : '';
                        $str = $nickname.$language.$city.$province.$country;
                        if(!empty($str))//用户唯一标识
                        {
                            $userInfos = Redis::get(base64_encode($str));
                            if($userInfos)
                            {
                                $userInfo = $userInfos;
                            }
                        }
                    }
                    var_dump($users);
                    var_dump($userInfo);*/
                    //判断是否已经关注过了
                    //var_dump($users);
                    $res = DB::table('wechat_user')->where(['openid'=>$users['openid']])->first();
                    if( $res )
                    {
                        $result = '';
                    }else
                    {
                        $this->newUserSubStatus($users);
                    }
                    $type = $object->EventKey;
                    //$type = json_decode($type);
                    if($type=='qrscene_1'){
                        $result = $this->transmitImage($object,'-JGoyEhSkfHTdh5CyJUSTpX7602GasFBAnF9X75DZUs');
                    }elseif($type=='qrscene_2'){
                        $result = $this->transmitImage($object,'-JGoyEhSkfHTdh5CyJUSTp6wTu126TzGwU4UPG6ka_M');
                    }elseif ($type=='qrscene_3'){
                        $result = $this->transmitImage($object,'-JGoyEhSkfHTdh5CyJUSTp5KBlEg9ldfFmmlvmCw_gk');
                    }elseif ($type=='qrscene_4'){
                        $result = $this->transmitImage($object,'-JGoyEhSkfHTdh5CyJUSTkQkP_OChH5tUCfFajCcyKs');
                    }
                    else{
                        $result = $this->transmitText($object, '感谢您的关注！您已成为【本宫艺术甜品】的尊享会员！快快点击屏幕下方的菜单栏查看您的专属特权吧~');

                    }
                    break;
                case "unsubscribe"://取消关注事件
                    //if ($debug) savelog('fans_error1','取关了'.$object->ToUserName);
                    savelog('fans_error1','取关了:'.$object->ToUserName);
                    $result = '';
                    break;
                case "SCAN":  //扫描二维码
                    $type = $object->EventKey;
                    $type = json_decode($type);
                    if($type ==1 ){
                        $result = $this->transmitImage($object,'-JGoyEhSkfHTdh5CyJUSTpX7602GasFBAnF9X75DZUs');
                    }elseif($type ==2 ){
                        $result = $this->transmitImage($object,'-JGoyEhSkfHTdh5CyJUSTp6wTu126TzGwU4UPG6ka_M');
                    }elseif ($type==3){
                        $result = $this->transmitImage($object,'-JGoyEhSkfHTdh5CyJUSTp5KBlEg9ldfFmmlvmCw_gk');
                    }elseif ($type==4){
                        $result = $this->transmitImage($object,'-JGoyEhSkfHTdh5CyJUSTkQkP_OChH5tUCfFajCcyKs');
                    }
                    savelog('newweixinuser.log', $type);
                    break;
                case "user_get_card":  //领取会员卡
                    $UserCardCode = $object->UserCardCode;  //会员卡号
                    $wx_open_openid = $object->FromUserName;  //公众号openid
                    $wx_open_unionId = $object->UnionId;  //公众号UnionId
                    $ibrand_user = DB::table('ibrand_user')->where(['unionid'=>$wx_open_unionId])->first();
                    if($ibrand_user){
                        $member = DB::table('member')->where(['openid'=>$ibrand_user->openid])->first();
                        if(!$member){
                            DB::table('member')->insert(['openid'=>$ibrand_user->openid,'membership_number'=>$UserCardCode,'bonus'=>0,'code'=>$UserCardCode,'created_at'=>date('Y-m-d H:i:s',time())]);
                        }
                    }


            }
            //$result = $this->transmitText($object, $content);
            return $result;
        }catch (\Exception $ex) {
            var_dump($ex->getMessage().$ex->getLine());
        }

     }


    private function newUserSubStatus($users)
    {
            $info = [];
            $info['subscribe'] = $users['subscribe'];
            $info['openid'] = $users['openid'];
            $info['nickname'] = $users['nickname'];
            $info['sex'] = $users['sex'];
            $info['city'] = $users['city'];
            $info['province'] = $users['province'];
            $info['headimgurl'] = $users['headimgurl'];
            $info['subscribe_time'] = $users['subscribe_time'];
            $info['unionid'] = $users['unionid'];
            $info['subscribe_scene'] = $users['subscribe_scene'];
            $info['qr_scene'] = $users['qr_scene'];
            $info['qr_scene_str'] = $users['qr_scene_str'];
            DB::table('wechat_user')->insertGetId($info);

    }

    //接收文本消息
    private function receiveText($object, $url='www.osv.cn')
    {
        $keyword = trim($object->Content);
        if (strstr($keyword, "文本"))
        {
              $content = "这是个文本消息";
        }elseif( trim($keyword) == '666'  )//发券
        {
             $result = $this->newreceiveCoupon($object,'');
             return $result;
        }elseif( trim($keyword) == '1' )//发券
        {
            $result = $this->transmitImage($object,'-JGoyEhSkfHTdh5CyJUSToknll0jMlj5BM-8gyagaiA');
            //$result = $this->transmitImage($object,'-JGoyEhSkfHTdh5CyJUSTpX7602GasFBAnF9X75DZUs');  1
            //$result = $this->transmitImage($object,'-JGoyEhSkfHTdh5CyJUSTp6wTu126TzGwU4UPG6ka_M');  2
            return $result;
        }
        elseif( trim($keyword) == '2')//发券
        {
            $content = array();
            $content[] = array("Title"=>"玩抖音赢大奖，给本宫乐一下 活动等你来挑战！", "Description"=>"", "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_jpg/a8aUz8FLWxjokb5vUKBMXlDZ2PSiaq4YoGkJHDoPI2IGwiaU9QtOWKrbRsbeHu0ibSxnJQGmFaZLTYwQp3eRzXKFQ/0","Url" =>"https://mp.weixin.qq.com/s?__biz=MzA4ODQ2OTQ2Ng==&mid=2650827791&idx=1&sn=1571d90bf7a5558504f7d8471379b9cf&chksm=8bdd76babcaaffac0b3a1b997a67d26e780460ac047564285b315550502cfe5047db4f185bc6&token=2113131505&lang=zh_CN#rd");
        }else if (strstr($keyword, "单图文"))
        {
             $content = array();
             $content[] = array("Title"=>"单图文标题",  "Description"=>"单图文内容", "PicUrl"=>"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg", "Url" =>"http://www.baidu.com");
        }else if (strstr($keyword, "图文") || strstr($keyword, "多图文"))
        {
            $content = array();
            $content[] = array("Title"=>"多图文1标题", "Description"=>"", "PicUrl"=>"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg", "Url" =>"http://www.baidu.com");
            $content[] = array("Title"=>"多图文2标题", "Description"=>"", "PicUrl"=>"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg", "Url" =>"http://www.baidu.com");
            $content[] = array("Title"=>"多图文3标题", "Description"=>"", "PicUrl"=>"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg", "Url" =>"http://www.baidu.com");
        }else if (strstr($keyword, "音乐"))
        {
            $content = array();
            $content = array("Title"=>"最炫民族风", "Description"=>"歌手：凤凰传奇", "MusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3", "HQMusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3");
        }else{
            $content = '本宫PavoMea,
意为“我的美丽星座”，
我们用精致烘焙的工艺，
为每个追求完美品质的你，
打造健康、艺术和时尚的美味生活。

本宫零食铺正式开张啦！
请点击下方【零食铺】，
健康的，好吃、好看、好玩的【男仆蛋糕】【本宫鹰嘴脆】
正扑面而来！';
        }

        if(is_array($content))
        {
            if (isset($content[0]))
            {
                 $result = $this->transmitNews($object, $content);
            }else if (isset($content['MusicUrl']))
            {
                 $result = $this->transmitMusic($object, $content);
            }
        }else
        {
            $result = $this->transmitText($object, $content);
        }
        return $result;
    }

    //回复文本消息
     private function transmitText($object, $content)
     {
         if (!isset($content) || empty($content)){
             return "";
         }
         $xmlTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                 </xml>";
         $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
         return $result;
    }

    //回复图片消息
    private function transmitImage($object, $content)
    {
        if (!isset($content) || empty($content)){
            return "";
        }
        $xmlTpl = "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[image]]></MsgType>
                <Image>
                <MediaId><![CDATA[%s]]></MediaId>
                </Image>
                <FuncFlag>0</FuncFlag>
                </xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }

   //回复图文消息
     private function transmitNews($object, $newsArray)
     {
        if(!is_array($newsArray))
        {
                   return;
        }
        $itemTpl = "<item>
                        <Title><![CDATA[%s]]></Title>
                         <Description><![CDATA[%s]]></Description>
                         <PicUrl><![CDATA[%s]]></PicUrl>
                         <Url><![CDATA[%s]]></Url>
                    </item>";
         $item_str = "";
         foreach ($newsArray as $item)
         {
             $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
         }
         $xmlTpl = "<xml>
                         <ToUserName><![CDATA[%s]]></ToUserName>
                         <FromUserName><![CDATA[%s]]></FromUserName>
                         <CreateTime>%s</CreateTime>
                         <MsgType><![CDATA[news]]></MsgType>
                         <ArticleCount>%s</ArticleCount>
                         <Articles>$item_str</Articles>
                     </xml>";
         $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
         return $result;
     }

     //回复音乐消息
     private function transmitMusic($object, $musicArray)
     {
        $itemTpl = "<Music>
                         <Title><![CDATA[%s]]></Title>
                         <Description><![CDATA[%s]]></Description>
                         <MusicUrl><![CDATA[%s]]></MusicUrl>
                         <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
                    </Music>";
         $item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);
         $xmlTpl = "<xml>
                     <ToUserName><![CDATA[%s]]></ToUserName>
                     <FromUserName><![CDATA[%s]]></FromUserName>
                     <CreateTime>%s</CreateTime>
                     <MsgType><![CDATA[music]]></MsgType>
                     $item_str
                    </xml>";
         $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
         return $result;
     }
    /**
     * @param array $arr
     * @return array()
     * 获取公众号信息
     */
    private function getWechat($arr = array())
    {
//        if( empty($arr) || count($arr) <= 0 )
//        {
//            return '';
//        }
//        if( !isset($arr['user_name']) || empty(trim($arr['user_name'])) )
//        {
//            return '';
//        }
//        $url = env('API_DOMAIN','cloud.osv.cn').'/merchant/getwechat/';
//        $data['user_name'] = trim($arr['user_name']);
//        $data['clientHash'] = trim($arr['clientHash']);
//        $data['appid'] = env('DEV_APPID','i50bpfzeg0x4633c');
//        $sign = getSign($data,env('DEV_KEY','l4e9zxyry458n3g1w2pbx4x9k2g8vtct'));
//        $data['sign'] = $sign;
//        $resp = Curl::to($url)
//            ->withContentType('application/json')
//            ->withData( $data )
//            ->asJsonRequest()
//            ->post();
//        $resp = json_decode($resp,true);
//        if( isset( $resp['success']) && $resp['success'] == 0 )
//        {
//            return ( isset($resp['data']) && !empty($resp['data']) )?$resp['data']:'';
//        }else
//        {
//            return '';
//        }

        if( empty($arr) || count($arr) <= 0 )
        {
            return '';
        }
        if( !isset($arr['user_name']) || empty(trim($arr['user_name'])) )
        {
            return '';
        }
        $wechat = wechats::select('wechats.*')
            ->leftJoin('client', 'wechats.channel_id', '=', 'client.uid')
            ->where(['wechats.user_name'=>$arr['user_name'],'wechats.is_valid'=>1,'wechats.status'=>1,'client.clientHash'=>$arr['clientHash']])
            ->first();
        return $wechat? $wechat->toArray() : '';
    }

    /**
     * 获取授权公众号方用户信息
     */
    private function getAuthInfo($authOpenid,$authAppid)
    {
        $authorizerAccess_token = $this->getToken();
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$authorizerAccess_token&openid=$authOpenid[0]&lang=zh_CN";
        $resp = Curl::to($url)->get();
        $resp = json_decode($resp,true);
        return $resp;
    }


    /**
     * 客服接口-发消息
     */
    public function createqrcode()
    {
        $authorizerAccess_token = $this->getToken();
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=$authorizerAccess_token";
        $res = Curl::to( $url )
            ->withContentType('application/json')
            ->withData(json_encode(['action_name'=>'QR_LIMIT_SCENE','action_info'=>['scene'=>['scene_id'=>1]]]))
            ->post();
        $resp = json_decode($res,true);
        return $resp;
    }


    /**
     * @param $appid
     * @param $appsecret
     * @return mixed
     * 获取token
     */
    public function getToken() {
        $access_token = Redis::get('lm_access_token_bengong_open');
        if(!$access_token)
        {
            // 如果是企业号用以下URL获取access_token
            //$url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appid&secret=$this->secret";
            $res = Curl::to($url)
                ->withData()
                ->get();
            $res = json_decode($res,true);
            $access_token = isset($res['lm_access_token_bengong_open'])?$res['lm_access_token_bengong_open']:'';
            if ($access_token)
            {
                Redis::setex('lm_access_token_bengong_open',7000,$access_token);
            }
        }
        return $access_token;
    }


 }
?>